/*
import React, {useState} from 'react';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, message, Upload} from 'antd';
import {UploadProps} from 'antd/lib/upload';


export type Props = {
  setImageUrlf: () => void;
};

const mockUploadResponse = (file: File): Promise<string> =>
  new Promise(resolve => {
    setTimeout(() => {
      // 这里应该是从服务器返回的图片URL，但为了示例，我们直接返回Base64编码的字符串
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.readAsDataURL(file);
    }, 1000);
  });

const UploadAvatar: React.FC<Props> = (props) => {
  const {setImageUrlf}=props;
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps['onChange'] = async (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      const url = await mockUploadResponse(info.file.originFileObj as File);
      setLoading(false);
      setImageUrl(url);
    }
  };

  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const uploadButton = (
    <Button style={{ border: 'none', background: 'none', padding: 0 }}>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </Button>
  );

  return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
        ) : (
          uploadButton
        )}
      </Upload>
  );
};

export default UploadAvatar;
*/

import React, {useEffect, useState} from 'react';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import type {UploadProps} from 'antd';
import {message, Upload} from 'antd';
import {uploadFileUsingPost} from "@/services/backend/fileController";
import {RcFile} from "antd/es/upload";


const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const UploadAvatar: React.FC<{ onUploadSuccess?: (imageUrl: string) => void ,initialImage: string}> =
  ({ onUploadSuccess,initialImage }) =>{
  const [loading, setLoading] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState<string>(initialImage|| '');

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <button style={{border: 0, background: 'none'}} type="button">
      {loading ? <LoadingOutlined/> : <PlusOutlined/>}
      <div style={{marginTop: 8}}>Upload</div>
    </button>
  );

    useEffect(() => {
      setImageUrl(initialImage);
    }, [initialImage]);

  // 图片上传
  const handleCustomUpload = async (options: { file: File | undefined; }) => {
    try {
      const response = await uploadFileUsingPost({biz: 'user_avatar'}, {}, options.file);
      if (response.code===0&&response.data) {
        setImageUrl(response.data);
        setLoading(false);
        message.success('上传成功!');
        if (onUploadSuccess) {
          onUploadSuccess(response.data); // 调用回调函数
        }
      } else {
        message.error('上传失败!');
      }
    } catch (error) {
      message.error('上传错误: ' + error);
    }
  };

  return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        onChange={handleChange}
        // @ts-ignore
        customRequest={handleCustomUpload}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{width: '100%'}}/> : uploadButton}
      </Upload>
  );
};

export default UploadAvatar;
